import {
  getShareAccountPage,
  saveCuesTopic,
  saveCuesTopicTreeAssignOrganization,
} from '@/services/api/api-cues-topic';
import { CloseOutlined, FolderOutlined, HomeOutlined, PlusOutlined } from '@ant-design/icons';
import { ProFormTextArea } from '@ant-design/pro-components';
import ProForm, {
  DrawerForm,
  ProFormDateTimeRangePicker,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-form';
import ProList from '@ant-design/pro-list';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { useAccess } from '@umijs/max';
import { Button, Divider, Empty, Space, message } from 'antd';
import Tree, { DataNode } from 'antd/es/tree';
import moment from 'moment';
import React, { useRef, useState } from 'react';

interface AddTopicProps {
  onRefurbish: (id: string) => void;
}

const AddTopic: React.FC<AddTopicProps> = ({ onRefurbish }) => {
  const access = useAccess();
  const actionRef = useRef<ActionType>();

  const formRef = useRef<ProFormInstance>();

  //选题计划
  const [topicPlans, setTopicPlans] = useState<CuesTopicBo.TopicPlanBo[]>([]);

  /**
   * 初始化树形数据
   */
  const [treeOrganizationData, setTreeOrganizationDataState] = useState<DataNode[]>();
  /**
   * 树形列表选择数据
   */
  const [checkedOrganizationIds, setCheckedOrganizationIdsState] = useState<any[]>([]);

  const [selectedShareAccountRowKeys, setSelectedShareAccountKeysState] = useState<React.Key[]>([]);

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          title: val.name,
          key: val.id,
          item: val,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
          icon:
            val.state === 1 ? (
              val.isFolder === 0 ? (
                <HomeOutlined />
              ) : (
                <FolderOutlined />
              )
            ) : (
              <CloseOutlined />
            ),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载权限详情
   * @param key
   */
  const loadOrganizationData = async () => {
    try {
      const response = await saveCuesTopicTreeAssignOrganization();
      if (response.code === 0) {
        const treeData = new Array<DataNode>();
        treeData.push({
          title: '融媒通',
          key: '0',
          item: { id: '0', name: '融媒通' },
          children: readyTreeData(response.data),
        });
        setTreeOrganizationDataState(treeData);
      }
    } catch (error) {}
  };

  return (
    <DrawerForm
      key="add_promotion_task_drawer_form_douyin"
      title="创建选题计划"
      drawerProps={{
        maskClosable: false,
        destroyOnClose: true,
      }}
      formRef={formRef}
      trigger={
        <Button key="create" type="primary">
          <PlusOutlined />
          创建选题计划
        </Button>
      }
      initialValues={{
        isDemandClipboard: 1,
        deadline: [Date.now()],
      }}
      onOpenChange={(visible: boolean) => {
        if (visible) {
          //加载权限树请求网络
          loadOrganizationData();
        } else {
          setTopicPlans([]);
        }
      }}
      onValuesChange={(values) => {
        console.log('=====', values);
      }}
      onFinish={async (values) => {
        console.log(topicPlans);
        if (access.线索上报x选题计划x计划列表x创建计划x多条选题计划) {
          if (topicPlans.length === 0) {
            message.warning('请添加至少一个任务');
            return false;
          }
        }
        let deadline = '';
        if (values.deadline !== undefined && values.deadline.length === 2) {
          deadline = values.deadline[1];
        }

        let isAssign: number = 0;

        if (
          values.assignOrganizationNames !== undefined &&
          values.assignOrganizationNames.length > 0
        ) {
          isAssign = 1;
          const checkNames = formRef.current?.getFieldValue('assignOrganizationNames') as [];
          if (checkNames) {
            const checkOrgs = new Array();
            checkedOrganizationIds?.forEach((item) => {
              if (checkNames.includes(item?.name)) {
                checkOrgs.push(item);
              }
            });
            values.assignOrganizationIds = Array.from(checkOrgs, ({ id }) => id);
          }
        }

        let isShare: number = 0;

        if (values.shareAccountNames !== undefined && values.shareAccountNames.length > 0) {
          isShare = 1;
          values.shareAccountNames = undefined;
          values.shareAccountRows = undefined;
          values.shareAccountIds = selectedShareAccountRowKeys;
        }

        if (!access.线索上报x选题计划x计划列表x创建计划x多条选题计划) {
          const id = moment().format();
          let topicPlans = [
            {
              id: id,
              name: values.name,
              describes: values.describes,
            },
          ];
          const response = await saveCuesTopic({
            ...values,
            deadline,
            isAssign,
            isShare,
            topicPlans,
          });

          if (response.code === 0) {
            message.success('提交成功');
            // setTopicPlans([]);
            onRefurbish(response.data);
            return true;
          } else {
            return false;
          }
        } else {
          const response = await saveCuesTopic({
            ...values,
            deadline,
            isAssign,
            isShare,
            topicPlans,
          });

          if (response.code === 0) {
            message.success('提交成功');
            setTopicPlans([]);
            onRefurbish(response.data);
            return true;
          } else {
            return false;
          }
        }
      }}
    >
      <ProForm.Group>
        <ProFormText
          width="xl"
          name="name"
          label="标题"
          rules={[{ required: true, message: '请输入标题' }]}
          fieldProps={{
            allowClear: true,
            maxLength: 200,
          }}
        />
        <ProFormDateTimeRangePicker
          rules={[{ required: true, message: '这是必填项' }]}
          width="xl"
          name="deadline"
          label="任务执行截止时间"
          tooltip="到达截止时候后，系统关闭单位报送渠道"
          fieldProps={{
            disabled: [true, false],
            ranges: {
              后5天: [moment(), moment().add(5, 'days')],
              后10天: [moment(), moment().add(10, 'days')],
              后15天: [moment(), moment().add(15, 'days')],
              后20天: [moment(), moment().add(20, 'days')],
            },
            format: 'YYYY-MM-DD HH:mm:ss',
            defaultValue: [moment(), moment().add(5, 'days')],
          }}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormSelect
          name="assignOrganizationNames"
          label="指派报送单位（不选择，默认推送给所有部门，不包含融媒体中心）"
          showSearch
          fieldProps={{
            mode: 'multiple',
            allowClear: true,
            showSearch: true,
            showArrow: false,
            open: false,
            optionFilterProp: 'children',
            filterOption: (input: any, option: any) => {
              console.log(option);
              // return option.options.filter((item: any) => item.label.includes(input));
              return option.label.includes(input);
            },
            listHeight: 500,
            style: {
              width: 488,
            },
          }}
          addonAfter={
            <DrawerForm
              width="500px"
              title="指派报送单位"
              trigger={<a key="activeSaveAssign">点击添加</a>}
              autoFocusFirstInput
              drawerProps={{
                destroyOnClose: true,
              }}
              onVisibleChange={(visible: boolean) => {
                if (visible) {
                  const checkNames = formRef.current?.getFieldValue(
                    'assignOrganizationNames',
                  ) as [];
                  if (checkNames) {
                    const checkOrgs = new Array();
                    checkedOrganizationIds?.forEach((item) => {
                      if (checkNames.includes(item?.name)) {
                        checkOrgs.push(item);
                      }
                    });
                    setCheckedOrganizationIdsState(checkOrgs);
                  }
                }
              }}
              submitter={false}
            >
              {treeOrganizationData && treeOrganizationData.length ? (
                <Tree
                  defaultExpandAll
                  showLine={{ showLeafIcon: false }}
                  showIcon={true}
                  treeData={treeOrganizationData}
                  checkedKeys={checkedOrganizationIds.map((item) => {
                    return item.id;
                  })}
                  checkable
                  onCheck={(checkedKeys, e) => {
                    const checkOrgs = new Array();

                    e.checkedNodesPositions?.forEach((item) => {
                      if (item.node?.item?.isFolder === 0) {
                        checkOrgs.push(item.node.item);
                      }
                    });

                    setCheckedOrganizationIdsState(checkOrgs);

                    formRef.current?.setFieldsValue({
                      assignOrganizationNames: Array.from(checkOrgs, ({ name }) => name),
                    });
                  }}
                />
              ) : (
                <Empty />
              )}
            </DrawerForm>
          }
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormSelect
          name="shareAccountNames"
          label="指派其他可阅读、录用记者（不选择，只有自己可以阅读和录用）"
          showSearch
          fieldProps={{
            mode: 'multiple',
            allowClear: true,
            showSearch: true,
            showArrow: false,
            open: false,
            optionFilterProp: 'children',
            filterOption: (input: any, option: any) => {
              console.log(option);
              // return option.options.filter((item: any) => item.label.includes(input));
              return option.label.includes(input);
            },
            listHeight: 500,
            style: {
              width: 488,
            },
          }}
          addonAfter={
            <DrawerForm
              width="500px"
              title="指派其他可阅读、录用记者"
              trigger={<a key="activeSaveAssign">点击添加</a>}
              autoFocusFirstInput
              drawerProps={{
                destroyOnClose: true,
              }}
              onVisibleChange={(visible: boolean) => {
                if (visible) {
                  const checkNames = formRef.current?.getFieldValue('shareAccountNames') as [];
                  if (checkNames) {
                    const checkRows = formRef.current?.getFieldValue('shareAccountRows') as [];

                    const rows = checkRows.filter((item) => {
                      return checkNames.includes(item.name);
                    });

                    const ids = rows.map((item) => item.id);

                    setSelectedShareAccountKeysState(ids);
                  }
                }
              }}
              submitter={false}
            >
              <ProTable<CuesTopicData.UserAccount>
                ghost
                rowSelection={{
                  selectedRowKeys: selectedShareAccountRowKeys,
                  type: 'checkbox',
                  onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
                    const names = selectedRows.map((item: { name: any }) => item.name);

                    setSelectedShareAccountKeysState(selectedRowKeys);
                    formRef.current?.setFieldsValue({
                      shareAccountNames: names,
                      shareAccountRows: selectedRows,
                    });
                  },
                }}
                tableAlertRender={false}
                columns={[
                  {
                    title: '单位',
                    key: 'or',
                    dataIndex: 'organizationName',
                    hideInSearch: true,
                    width: 200,
                  },
                  {
                    title: '姓名',
                    key: 'name',
                    dataIndex: 'name',
                  },
                ]}
                request={async (params = {}) => {
                  const response = await getShareAccountPage({
                    ...params,
                  });
                  return Promise.resolve({
                    data: response.data.data,
                    total: response.data.total,
                    success: response.code === 0,
                  });
                }}
                rowKey="id"
                tableLayout="fixed"
                dateFormatter="string"
                headerTitle={false}
                bordered
                options={{
                  search: {
                    name: 'name',
                    onSearch: (keyword: string) => {
                      setSelectedShareAccountKeysState([]);
                      formRef.current?.setFieldsValue({
                        name: undefined,
                      });
                      return true;
                    },
                  },
                }}
                search={false}
                pagination={{
                  showQuickJumper: false,
                  showSizeChanger: false,
                  defaultPageSize: 100,
                  showLessItems: false,
                }}
              />
            </DrawerForm>
          }
        />
      </ProForm.Group>
      {!access.线索上报x选题计划x计划列表x创建计划x多条选题计划 ? (
        <ProForm.Group>
          <ProFormTextArea
            colProps={{ span: 24 }}
            rules={[{ required: true, message: '请输入选题内容' }]}
            name="describes"
            label="选题内容"
            placeholder="请输入描述（支持换行输入）"
            width="xl"
          />
        </ProForm.Group>
      ) : (
        <>
          <Divider orientation="left" plain>
            添加计划
          </Divider>
          <div style={{ textAlign: 'right' }}>
            <Space align="center">
              <Button
                key="add_topic_plan"
                size="small"
                type="primary"
                onClick={() => {
                  const id = moment().format();
                  setTopicPlans([
                    ...topicPlans,
                    {
                      id,
                      name: '',
                      describes: '',
                    },
                  ]);
                  actionRef?.current?.startEditable(id);
                }}
              >
                创建
              </Button>
            </Space>
          </div>
          <ProList
            actionRef={actionRef}
            ghost
            rowKey="id"
            defaultData={[]}
            dataSource={topicPlans}
            editable={{
              type: 'multiple',
              onSave: async () => {
                return true;
              },
              onValuesChange: (record, dataSource) => {
                const datas = new Array();

                dataSource.forEach((item) => {
                  if (item.id !== undefined) {
                    datas.push(item);
                  }
                });
                setTopicPlans(datas);
                console.log(datas);
              },
              actionRender: (row, config, defaultDom) => [defaultDom.delete],
            }}
            toolBarRender={() => {
              return [];
            }}
            onDataSourceChange={setTopicPlans}
            metas={{
              title: {
                dataIndex: 'name',
                fieldProps: { maxLength: 100, placeholder: '请输入名称' },
                formItemProps: {
                  style: {
                    width: 666,
                    marginTop: 5,
                    marginBottom: 5,
                  },

                  rules: [
                    {
                      required: true,
                      message: '这是必填项',
                      validator(_, value) {
                        if (!value) {
                          return Promise.reject(new Error('这是必填项'));
                        }

                        const reg = /^\s+|\s+$/g;

                        const strValue = value.replace(reg, '');

                        console.log('=========', strValue);

                        if (strValue.length == 0) {
                          return Promise.reject(new Error('这是必填项'));
                        }

                        if (value instanceof Object) {
                          return Promise.reject(new Error('请输入正确数据格式'));
                        }

                        return Promise.resolve();
                      },
                    },
                  ],
                },
              },
              description: {
                dataIndex: 'describes',
                fieldProps: {
                  rows: 6,
                  allowClear: true,
                  maxLength: 3000,
                  placeholder: '请输入描述（支持换行输入）',
                },
                formItemProps: {
                  style: {
                    marginTop: 5,
                    marginBottom: 5,
                  },
                },
              },
              actions: {
                render: () => [],
              },
            }}
          />
        </>
      )}
    </DrawerForm>
  );
};
export default AddTopic;
